import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getPost } from '../../../actions/actions';
import PropTypes from 'prop-types';
import ErrorDisplay from '../../common/ErrorDisplay';
import Loading from '../../common/Loading';
import PostCard from './PostCard';
import Comments from './../comments/Comments';
import { Button } from '@material-ui/core';
import { withRouter } from 'react-router-dom';
import { withStyles } from '@material-ui/core/styles';
import withWidth from '@material-ui/core/withWidth/withWidth';
import compose from 'recompose/compose';

const styles = {
    flexBox: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100px',
    },
};

class SinglePost extends Component {
    constructor(props) {
        super(props);
        this.backToHome = this.backToHome.bind(this);
    };

    componentWillMount() {
        this.props.getPost(this.props.slug);
    }

    backToHome() {
        this.props.history.push('/');
    };

    render() {
        const {classes, post} = this.props;
        const {title} = post;

        return (
            <div>
                {
                    !title && !this.props.error && <Loading/>
                }
                {
                    this.props.error &&
                    <ErrorDisplay
                        message={this.props.error}
                    />
                }
                {
                    title &&
                    <PostCard post={this.props.post}/>
                }
                {
                    title && !this.props.error &&
                    <Comments slug={this.props.slug}/>
                }
                <div className={classes.flexBox}>
                    <Button variant="outlined" color="primary" onClick={this.backToHome}>
                        返回首页
                    </Button>
                </div>
            </div>
        );
    }
}

SinglePost.propTypes = {
    slug: PropTypes.string,
    post: PropTypes.object,
    error: PropTypes.string,
    getPost: PropTypes.func,
    history: PropTypes.object,
    classes: PropTypes.object,
};

const mapStateToProps = state => {
    return {
        post: state.posts.current,
        error: state.posts.error,
    };
};

const mapDispatchToProps = dispatch => {
    return {
        getPost: slug => dispatch(getPost(slug)),
    };
};

export default withRouter(compose(withStyles(styles), withWidth())(connect(mapStateToProps, mapDispatchToProps)(SinglePost)));
